package org.devf.fork.imsimulator.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * TcpWriteChannel related
 *
 * @author wanghuafu
 * @since 1.0  2023/9/12 15:32
 */
public class TcpWriteChannel implements Channel {

    private final OutputStream outputStream;

    public TcpWriteChannel(OutputStream socketOutputStream) {
        outputStream = socketOutputStream;
    }

    @Override
    public boolean write(String message) {
        try {
            System.out.println("发送指令："+message);
            outputStream.write(buildData(message));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    private byte[] buildData(String vData) {
        int tLength = vData.getBytes(StandardCharsets.UTF_8).length;
        byte[] tLengthByte = new byte[4];
        tLengthByte[3] = (byte) ((tLength >> 24) & 0xFF);
        tLengthByte[2] = (byte) ((tLength >> 16) & 0xFF);
        tLengthByte[1] = (byte) ((tLength >> 8) & 0xFF);
        tLengthByte[0] = (byte) (tLength & 0xFF);

        ByteBuffer tByteArray = ByteBuffer.allocate(4 + tLength);
        tByteArray.put(tLengthByte);
        tByteArray.put(vData.getBytes(StandardCharsets.UTF_8));

        return tByteArray.array();
    }
}
